﻿using Microsoft.VisualStudio.TextTemplating;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ABPGenerator.Db
{
    class VSManagementStrategy : ManagementStrategy
    {
        private EnvDTE.ProjectItem templateProjectItem;

        internal VSManagementStrategy(ITextTemplatingEngineHost host) : base(host)
        {
            IServiceProvider hostServiceProvider = (IServiceProvider)host;
            if (hostServiceProvider == null)
                throw new ArgumentNullException("Could not obtain hostServiceProvider");

            EnvDTE.DTE dte = (EnvDTE.DTE)hostServiceProvider.GetService(typeof(EnvDTE.DTE));
            if (dte == null)
                throw new ArgumentNullException("Could not obtain DTE from host");

            templateProjectItem = dte.Solution.FindProjectItem(host.TemplateFile);
        }
        //创建文件
        internal override void CreateFile(String fileName, String content)
        {
            base.CreateFile(fileName, content);
            ((EventHandler)delegate { templateProjectItem.ProjectItems.AddFromFile(fileName); }).BeginInvoke(null, null, null, null);
        }
        //删除文件
        internal override void DeleteFile(String fileName)
        {
            ((EventHandler)delegate { FindAndDeleteFile(fileName); }).BeginInvoke(null, null, null, null);
        }
        //根据文件名删除文件
        private void FindAndDeleteFile(String fileName)
        {
            foreach (EnvDTE.ProjectItem projectItem in templateProjectItem.ProjectItems)
            {
                if (projectItem.get_FileNames(0) == fileName)
                {
                    projectItem.Delete();
                    return;
                }
            }
        }
    }

}
